package com.zengqingfa.springboot.redis.rest;

import com.zengqingfa.springboot.redis.dto.UserInfo;
import com.zengqingfa.springboot.redis.service.RedisServiceInterface;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

/**
 * @fileName: RedisController
 * @author: zengqf3
 * @date: 2021-3-5 10:24
 * @description:
 */
@RestController
@RequestMapping("/redis")
@Slf4j
public class RedisController {

    @Autowired
    private RedisServiceInterface redisService;

    @GetMapping("/getList")
    public Object getList() {
        return redisService.getList();
    }

    @PostMapping("/add")
    public String add(@RequestBody UserInfo userInfo) {
        return redisService.add(userInfo);
    }

    @GetMapping("/delete")
    public String delete(String key) {
        String remove = redisService.delete(key);
        return remove;
    }

    @PostMapping("/update")
    public String update(@RequestBody UserInfo userInfo) {
        String update = redisService.update(userInfo);
        return update;
    }


    @GetMapping("/getByKey")
    public String getByKey(String key) {
        return redisService.getByKey(key);
    }

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 测试节点挂了哨兵重新选举新的master节点，客户端是否能动态感知到
     * 新的master选举出来后，哨兵会把消息发布出去，客户端实际上是实现了一个消息监听机制，
     * 当哨兵把新master的消息发布出去，客户端会立马感知到新master的信息，从而动态切换访问的masterip
     */
    @RequestMapping("/sentinel")
    public void sentinel() {
        int i = 1;
        while (true) {
            try {
                stringRedisTemplate.opsForValue().set("shenlongfeixian" + i, i + "");
                redisTemplate.opsForValue().set("slfx" + i, i + "");
                System.out.println("设置key：" + "shenlongfeixian" + i);
                i++;
                Thread.sleep(1000);
            } catch (Exception e) {
                log.error("错误：", e);
            }
        }
    }

    @GetMapping("/cluster")
    public String cluster(String key,String value) {
        stringRedisTemplate.opsForValue().set(key  ,value);
        String res = stringRedisTemplate.opsForValue().get(key);
        return res;
    }
}
